from flask import request, redirect, url_for, render_template, Blueprint

from src.day15.student_sys.student_manager import StuManager

stu_blue = Blueprint('student_router', __name__, url_prefix='/stu')
stu_manager = StuManager()


@stu_blue.route('/student')
def s_list():
    search_name = request.args.get('search')
    if search_name:
        return render_template('list_student.html', students=stu_manager.search_stu(search_name))
    return render_template('list_student.html', students=stu_manager.student)


@stu_blue.route('/add', methods=['get', 'post'])
def add():
    error = None
    if request.method == 'POST':
        name = request.form.get('name')
        age = request.form.get('age')
        s_class = request.form.get('s_class')
        email = request.form.get('email')
        address = request.form.get('address')
        error = stu_manager.judge_stu(name, age, s_class, email, address)
        if not error:
            stu_manager.add_stu(name, age, s_class, email, address)
            return redirect(url_for('student_router.s_list'))
    return render_template('add.html', error=error)


@stu_blue.route('/modify/<int:sid>', methods=['get', 'post'])
def modify(sid):
    student = stu_manager.get_student_by_id(sid)
    if not student:
        return '用户不存在', 404
    error = None
    if request.method == 'POST':
        name = request.form.get('name')
        age = request.form.get('age')
        s_class = request.form.get('class')
        email = request.form.get('email')
        address = request.form.get('address')
        error = stu_manager.judge_stu(name, age, s_class, email, address)
        if not error:
            stu_manager.modify_stu(sid, name, age, s_class, email, address)
            return redirect(url_for('student_router.s_list'))
    return render_template('modify_student.html', student=student, error=error)


@stu_blue.route('/delete/<int:sid>')
def delete(sid):
    stu_manager.delete_stu(sid)
    return redirect(url_for('student_router.s_list'))









